package com.songyuesheng.app.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * @Author song
 * @Date 2025/4/19 18:35
 */
@Service
public class OssUploaderService {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.access-key-id}")
    private String accessKeyId;

    @Value("${oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${oss.bucket-name}")
    private String bucketName;

    public String generatePresignedUrl(String objectKey) {
        OSS ossClient = buildOssClient();
        try {
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            URL url = ossClient.generatePresignedUrl(bucketName, objectKey, expiration);
            return url.toString();
        } finally {
            ossClient.shutdown();
        }
    }

    private OSS buildOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    private String generateObjectKey(File file, String directory) {
        return directory + file.getName();
    }

    public String uploadToOss(File file, String directory) {
        validateFile(file);
        OSS ossClient = buildOssClient();
        try {
            String objectKey = generateObjectKey(file, directory);
            ossClient.putObject(bucketName, objectKey, file);
            return objectKey;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            ossClient.shutdown();
        }
    }

    public void deleteFile(String objectKey) {
        OSS ossClient = buildOssClient();
        try {
            ossClient.deleteObject(bucketName, objectKey);
        } catch (Exception e) {
            throw new RuntimeException("文件删除失败", e);
        } finally {
            ossClient.shutdown();
        }
    }

    private void validateFile(File file) {
        if (!file.exists()) {
            throw new RuntimeException("文件不存在: " + file.getAbsolutePath());
        }
        if (file.length() == 0) {
            throw new RuntimeException("文件内容为空: " + file.getName());
        }
    }
}
